<template>
    <div class="product-main">
        <!-- <el-button type="primary" size="small" @click="saveData" class="product-save"
            >确定</el-button
        > -->
        <div class="product-info" style="padding-top: 16px; margin-left: 16px">
            <el-form :inline="true" :model="form" class="demo-form-inline">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="订单号" :label-width="'100px'">
                            <el-input
                                style="width: 80%"
                                size="small"
                                v-model="form.ddh"
                                placeholder="请输入"
                                @change="asveLocal"
                            ></el-input> </el-form-item
                    ></el-col>
                    <el-col :span="12">
                        <el-form-item label="客户名称" :label-width="'100px'">
                            <el-select
                                style="width: 80%"
                                size="small"
                                v-model="form.khmc"
                                placeholder="请选择"
                                @change="asveLocal"
                            >
                                <el-option
                                    :label="item.label"
                                    :value="item.value"
                                    v-for="item in optList1"
                                    :key="item.value"
                                ></el-option>
                            </el-select> </el-form-item
                    ></el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="下单日期" :label-width="'100px'">
                            <el-date-picker
                                style="width: 80%"
                                size="small"
                                v-model="form.xdrq"
                                type="datetime"
                                placeholder="选择日期"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                @change="asveLocal"
                            >
                            </el-date-picker></el-form-item
                    ></el-col>
                    <el-col :span="12">
                        <el-form-item label="结算货币" :label-width="'100px'">
                            <el-select
                                v-model="form.jshb"
                                placeholder="请选择"
                                size="small"
                                style="width: 80%"
                            >
                                <el-option
                                    :label="item.label"
                                    :value="item.value"
                                    v-for="item in optionJSHB"
                                    :key="item.value"
                                    @change="asveLocal"
                                ></el-option>
                            </el-select> </el-form-item
                    ></el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="订单税率" :label-width="'100px'">
                            <el-input
                                style="width: 80%"
                                size="small"
                                v-model="form.ddsl"
                                placeholder="请输入"
                                @change="asveLocal"
                            ></el-input> </el-form-item
                    ></el-col>
                    <el-col :span="12">
                        <el-form-item label="跟单人" :label-width="'100px'">
                            <el-select
                                style="width: 80%"
                                size="small"
                                v-model="form.gdr"
                                placeholder="请选择"
                                @change="asveLocal"
                            >
                                <el-option
                                    :label="item.label"
                                    :value="item.value"
                                    v-for="item in optList2"
                                    :key="item.value"
                                ></el-option>
                            </el-select> </el-form-item
                    ></el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="汇率" :label-width="'100px'">
                            <el-input
                                style="width: 80%"
                                size="small"
                                v-model="form.hl"
                                placeholder="请输入"
                                @change="asveLocal"
                            ></el-input> </el-form-item
                    ></el-col>
                    <el-col :span="12"
                        ><el-form-item label="订单交期" :label-width="'100px'">
                            <el-date-picker
                                style="width: 80%"
                                size="small"
                                v-model="form.ddjq"
                                type="datetime"
                                placeholder="选择日期"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                @change="asveLocal"
                            >
                            </el-date-picker
                        ></el-form-item>
                    </el-col>
                </el-row>
                <el-divider></el-divider>
                <el-row style="padding: 30px 0px 10px 0px">
                    <el-col :span="20">
                        <el-col :span="6">
                            <el-form-item label="产品型号" :label-width="'120px'">
                                <el-select
                                    v-model="form.cpxh"
                                    placeholder="产品型号"
                                    size="small"
                                    style="width: 98%"
                                    @change="changeCPXH"
                                >
                                    <el-option
                                        :label="item.label"
                                        :value="item.value"
                                        v-for="item in optionCPXH"
                                        :key="item.value"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="数量" :label-width="'120px'">
                                <el-input-number
                                    style="width: 98%"
                                    size="small"
                                    v-model="form.sl"
                                    placeholder="数字文本"
                                    @change="asveLocal"
                                ></el-input-number> </el-form-item
                        ></el-col>
                        <el-col :span="6">
                            <el-form-item label="单价" :label-width="'120px'">
                                <el-input-number
                                    style="width: 98%"
                                    size="small"
                                    v-model="form.dj"
                                    placeholder="数字文本"
                                    @change="asveLocal"
                                ></el-input-number> </el-form-item
                        ></el-col>
                        <el-col :span="6">
                            <el-form-item label="金额" :label-width="'120px'">
                                <el-input-number
                                    style="width: 98%"
                                    size="small"
                                    v-model="form.je"
                                    placeholder="数字文本"
                                    @change="asveLocal"
                                ></el-input-number> </el-form-item
                        ></el-col>
                    </el-col>
                    <el-col :span="4"></el-col>
                </el-row>
            </el-form>
            <el-image
                v-if="productData.materialUrl"
                class="product-img"
                style="
                    margin: 0px 20px 0px 10px;
                    width: 100px;
                    height: 100px;
                    border-radius: 5px;
                    object-fit: cover;
                "
                :src="origin + productData.materialUrl"
                :preview-src-list="[origin + productData.materialUrl]"
            ></el-image>
        </div>
        <div class="product-item">
            <el-collapse v-model="activeNames">
                <el-collapse-item
                    v-for="(item, index) in productData.materialList"
                    :key="item.materialId"
                    :name="index"
                >
                    <template slot="title">
                        <div class="product-item-title">
                            <span>{{ item.materialName }}</span>
                        </div>
                    </template>
                    <div class="product-item-container">
                        <div class="container-config" v-for="i in item.pzList" :key="i.pzID">
                            <!-- 左侧图片 -->
                            <div class="container-image">
                                <img :src="origin + i.pzUrl" :alt="i.pzSx" v-if="i.pzUrl" />
                            </div>
                            <!-- 右侧内容 -->
                            <div class="container-content">
                                <div class="container-title">{{ i.pzMc }}</div>
                                <el-input
                                    v-model="i.pzSx"
                                    placeholder="请选择"
                                    @focus="changeConfigAttr(i, item)"
                                ></el-input>
                            </div>
                        </div>
                    </div>
                </el-collapse-item>
            </el-collapse>
        </div>
        <!-- Dialog 对话框 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" append-to-body>
            <el-radio-group v-model="selectedValue" class="radio-group">
                <div v-for="(option, index) in options" :key="index" style="margin: 5px">
                    <el-radio :label="option.pz_sx" class="radio-item">
                        <div style="width: 200px; display: flex; algin-items: center">
                            <!-- option.pz_image_url -->
                            <div style="margin: 0px 20px 0px 10px; width: 50px; height: 50px">
                                <el-image
                                    v-if="option.pz_image_url"
                                    style="
                                        width: 50px;
                                        height: 50px;
                                        border-radius: 5px;
                                        object-fit: cover;
                                    "
                                    :src="origin + option.pz_image_url"
                                    :preview-src-list="[origin + option.pz_image_url]"
                                >
                                </el-image>
                            </div>
                            <span style="line-height: 50px; font-size: 16px; font-weight: bold">{{
                                option.pz_sx
                            }}</span>
                        </div>
                    </el-radio>
                </div>
            </el-radio-group>

            <!-- 底部操作按钮 -->
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="confirmSelection">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
    props: { value: String },
    computed: {},
    data() {
        return {
            dingdanId: "",
            activeNames: [0, 1, 2],
            productData: {
                materialList: [
                    // {
                    //     materialCode: "wlbm123",
                    //     materialName: "物料名称123",
                    //     materialId: "616223416873152069",
                    //     pzList: [
                    //         {
                    //             pzID: "629333148458577605",
                    //             pzMc: "物料配置2",
                    //             pzSx: "",
                    //             pzImage: "",
                    //             pzUrl: "",
                    //         },
                    //     ],
                    // },
                    // {
                    //     materialCode: "WLFLBH00000001",
                    //     materialName: "物料名称111",
                    //     materialId: "616279040310931013",
                    //     pzList: [
                    //         {
                    //             pzID: "629332760460291781",
                    //             pzMc: "物料配置名称1",
                    //             pzSx: "",
                    //             pzImage: "",
                    //             pzUrl: "",
                    //         },
                    //         {
                    //             pzID: "629333148458577605",
                    //             pzMc: "物料配置2",
                    //             pzSx: "",
                    //             pzImage: "",
                    //             pzUrl: "",
                    //         },
                    //     ],
                    // },
                    // {
                    //     materialCode: "WLBM",
                    //     materialName: "物料名称",
                    //     materialId: "629611879169289925",
                    //     pzList: [
                    //         {
                    //             pzID: "629332760460291781",
                    //             pzMc: "物料配置名称1",
                    //             pzSx: "",
                    //             pzImage: "",
                    //             pzUrl: "",
                    //         },
                    //     ],
                    // },
                ],
            },
            infoData: [],
            dialogVisible: false, // 控制对话框显示状态
            selectedValue: null, // 存储用户选中的选项
            options: [],
            dialogTitle: "",
            origin: "",
            optionCPXH: [
                // { code: "WLFLBH00000001", label: "物料名称111", value: "616279040310931013" },
                // { code: "wlbm123", label: "物料名称123", value: "616223416873152069" },
                // { code: "WLBM", label: "物料名称", value: "629611879169289925" },
            ],
            optList1: [
                { value: "客户01", label: "客户01" },
                { value: "客户02", label: "客户02" },
                { value: "客户03", label: "客户03" },
                { value: "客户04", label: "客户04" },
            ],
            optList2: [
                { value: "司马光‌", label: "司马光‌" },
                { value: "苏轼", label: "苏轼" },
                { value: "李白", label: "李白" },
                { value: "屈原", label: "屈原" },
                { value: "杜甫", label: "杜甫" },
                { value: "王羲之", label: "王羲之" },
                { value: "颜真卿", label: "颜真卿" },
                { value: "嬴政", label: "嬴政" },
            ],
            optionJSHB: [
                // { value: "02", label: "人名币" },
                // { value: "01", label: "美元" },
            ],
            form: {
                f_id: "",
                ddh: "DDH000003",
                khmc: "",
                xdrq: "",
                jshb: "02",
                ddsl: "12",
                gdr: "司马光‌",
                hl: "7.2",
                ddjq: "",
                cpxh: "",
                sl: "",
                dj: "",
                je: "",
            },
        };
    },
    async created() {
        this.dingdanId = this.value || "";
        this.form.f_id = this.value || "";
        this.origin = window.location.origin;

        // 获取当前时间
        let currentDate = new Date();
        let formattedDate = this.formatDate(currentDate);
        this.form.xdrq = formattedDate;

        let newDate = this.addMonth(currentDate);
        let formattedNewDate = this.formatDate(newDate);
        this.form.ddjq = formattedNewDate;

        await this.WitGlobal.requestCode("TYCP.dd.db.wlxxpz.getMaterial", {}).then((res) => {
            console.log("optionCPXH1", res);
            if (res.data) {
                this.optionCPXH = res.data.map((item) => {
                    console.log(JSON.parse(item.zsj_wlxx_wltp));
                    let wltp = JSON.parse(item.zsj_wlxx_wltp);
                    return {
                        ...item,
                        label: item.zsj_wlxx_wlmc,
                        value: item.f_id,
                        zsj_wlxx_url: wltp.length > 0 ? wltp[0].url : "",
                    };
                });
                if (this.form.f_id)
                    this.WitGlobal.requestCode("TYCP.dd.db.wlxxpz.getOrder", {
                        id: this.form.f_id,
                    }).then((res) => {
                        if (res.data) {
                            let data = res.data;
                            // 你好todu
                            this.infoData = data;
                            this.form.ddh = data[0].ddh;
                            this.form.khmc = data[0].khmc;
                            this.form.xdrq = data[0].xdrq;
                            this.form.jshb = data[0].jshb;
                            this.form.ddsl = data[0].ddsl;
                            this.form.gdr = data[0].gdr;
                            this.form.hl = data[0].hl;
                            this.form.ddjq = data[0].ddjq;
                            this.form.cpxh = data[0].cpxh;
                            this.form.sl = data[0].sl;
                            this.form.dj = data[0].dj;
                            this.form.je = data[0].je;
                            this.changeCPXH(this.form.cpxh, 1);
                        }
                    });
            }
            console.log("optionCPXH2", this.optionCPXH);
        });
        await this.WitGlobal.requestCode("TYCP.dd.db.wlxxpz.getMoney", {}).then((res) => {
            console.log("optionJSHB", res);
            if (res.data) {
                this.optionJSHB = res.data.map((item) => {
                    return { ...item, label: item.name, value: item.code };
                });
            }
        });
    },
    methods: {
        asveLocal() {
            let list = [];
            let num = 1;
            this.productData.materialList.forEach((item) => {
                if (item.pzList)
                    item.pzList.forEach((el, index) => {
                        const timestamp = Date.now();
                        let f_id = timestamp + "" + num.toString().padStart(3, "0");
                        num++;
                        list.push({
                            id: f_id,
                            materialId: item.materialId || "",
                            materialCode: item.materialCode || "",
                            materialName: item.materialName || "",
                            wlpzlineId: el.pzID || "",
                            wlpzlineUrl: el.pzUrl || "",
                            wlpzlineName: el.pzMC || "",
                            sxValue: el.pzSx || "",
                            orderCode: this.form.ddh || "",
                        });
                    });
            });
            console.log(1234, list);
            if (!this.form.f_id) {
                const timestamp = Date.now();
                this.form.f_id = timestamp + "" + "000";
            }
            localStorage.setItem(
                "dingDanShuJu",
                JSON.stringify({
                    a: { list },
                    b: this.form,
                    f_id: this.dingdanId,
                    ddh: this.form.ddh,
                })
            );
        },
        changeCPXH(val, flag = 0) {
            let selectedOption = this.optionCPXH.filter((option) => option.value == val);
            console.log("1selectedOption", selectedOption);
            this.productData.materialUrl = selectedOption[0].zsj_wlxx_url;
            console.log("image-src", this.origin + this.productData.materialUrl);
            this.WitGlobal.requestCode("TYCP.dd.db.wlxxpz.getWlpzByWlid", {
                id: selectedOption[0].f_id,
            }).then((res) => {
                if (res.data) {
                    this.productData = this.transformData(res.data);
                    if (flag) {
                        this.productData.materialList.forEach((item) => {
                            if (item.pzList)
                                item.pzList.forEach((el, index) => {
                                    let curData = this.infoData.filter((i) => i.pz_id == el.pzID);
                                    if (curData.length > 0) {
                                        this.$set(el, "id", curData[0].f_id);
                                        el.pzSx = curData[0].pz_sx;
                                        el.pzUrl = curData[0].pz_url;
                                    }
                                });
                        });
                    }
                }
                this.$forceUpdate();
            });
            this.asveLocal();
        },
        changeConfigAttr(i, item) {
            this.options = [];
            this.WitGlobal.requestCode("TYCP.dd.db.wlxxpz.getWlpzLine", { id: i.pzID }).then(
                (res) => {
                    let list = res.data;
                    this.options = list.map((item) => {
                        return {
                            pz_image_name:
                                JSON.parse(item.pz_image).length > 0
                                    ? JSON.parse(item.pz_image)[0].name
                                    : "",
                            pz_image_url:
                                JSON.parse(item.pz_image).length > 0
                                    ? JSON.parse(item.pz_image)[0].url
                                    : "",
                            pz_image_fileId:
                                JSON.parse(item.pz_image).length > 0
                                    ? JSON.parse(item.pz_image)[0].fileId
                                    : "",
                            pz_sx: item.pz_sx || "",
                        };
                    });
                }
            );
            this.dialogMaterial = item.materialId;
            this.dialogPz = i;
            this.dialogTitle = i.pzMc;
            this.dialogVisible = true; // 打开对话框
        },
        closeDialog() {
            this.dialogVisible = false; // 关闭对话框
        },
        confirmSelection() {
            let selectedOption = this.options.find((option) => option.pz_sx === this.selectedValue);
            this.productData.materialList.forEach((item) => {
                if (item.materialId == this.dialogMaterial) {
                    item.pzList.forEach((el) => {
                        if (el.pzID == this.dialogPz.pzID) {
                            this.$set(el, "pzSx", selectedOption.pz_sx);
                            this.$set(el, "pzUrl", selectedOption.pz_image_url);
                            this.$set(el, "pzImage", selectedOption.pz_image_name);
                        }
                    });
                }
            });
            this.asveLocal();
            this.closeDialog();
        },
        addMonth(date) {
            let newDate = new Date(date); // 复制当前日期
            newDate.setMonth(date.getMonth() + 1); // 增加一个月
            return newDate;
        },
        formatDate(date) {
            // 获取年份、月份、日期、小时、分钟和秒
            let year = date.getFullYear();
            let month = date.getMonth() + 1; // 月份从0开始，所以要加1
            let day = date.getDate();
            let hours = date.getHours();
            let minutes = date.getMinutes();
            let seconds = date.getSeconds();

            // 格式化成两位数
            month = month < 10 ? "0" + month : month;
            day = day < 10 ? "0" + day : day;
            hours = hours < 10 ? "0" + hours : hours;
            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            // 返回格式化后的日期字符串
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        transformData(data) {
            const grouped = {}; // 用于按 material_code 分组
            const result = {
                cpxh: "",
                materialTp: "",
                materialUrl: "",
                materialList: [],
            };
            // 遍历数据
            for (let i = 0; i < data.length; i++) {
                const item = data[i];
                const materialCode = item.material_code;
                const materialName = item.material_name;
                const materialId = item.material_id;

                // 解析 material_tp 并获取 main_image 和其 URL
                let materialTp = item.material_tp || "[]";
                let materialTpParsed = [];
                let materialUrl = "";

                try {
                    materialTpParsed = JSON.parse(materialTp);
                    materialUrl = materialTpParsed[0]?.url || "";
                } catch (e) {
                    console.error("解析 material_tp 出错: ", e.message);
                }

                // 如果 material_code 不在分组中，初始化结构
                if (!grouped[materialCode]) {
                    grouped[materialCode] = {
                        materialCode: materialCode,
                        materialName: materialName,
                        materialId: materialId,
                        pzList: [],
                    };
                }

                // 将物料配置项添加到 pzList
                grouped[materialCode].pzList.push({
                    pzID: item.pz_id,
                    pzMc: item.pz_mc,
                    pzSx: "",
                    pzImage: "",
                    pzUrl: "",
                });

                // 更新 result 的主物料信息
                if (i === 0) {
                    result.cpxh = item.main_id || "";
                    result.materialTp = materialTp;
                    result.materialUrl = materialUrl;
                }
            }

            // 将分组后的数据转换为 materialList
            result.materialList = Object.values(grouped);
            return result;
        },
    },
};
</script>

<style scoped>
.product-main {
    position: relative;
}
.product-save {
    width: 74px;
    height: 32px;
    font-size: 16px;
    position: absolute;
    right: 20px;
    top: -40px;
    color: #fff;
    background-color: #1677ff;
    border-color: #1677ff;
}
.product-info {
    position: relative;
}

.product-img {
    position: absolute;
    right: 0;
    bottom: 0;
}

.radio-group {
    gap: 10px; /* 单选组之间的间距 */
}

.radio-item {
    display: flex;
    align-items: center;
}

.option-image {
    margin: 0px 20px 0px 10px;
    width: 50px;
    height: 50px;
    border-radius: 5px; /* 图片圆角 */
    object-fit: cover; /* 保证图片比例不失真 */
}

.option-name {
    line-height: 50px;
    font-size: 16px;
    font-weight: bold;
}

.product-item-container {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
}

.container-config {
    display: flex;
    align-items: center;
    border: 1px solid #ccc;
    border-radius: 8px;
    padding: 5px 10px 5px 10px;
    width: 15%;
    margin-left: 1.5%;
    margin-bottom: 10px;
    background-color: #fff;
}

.container-image {
    width: 80px;
    height: 80px;
}

.container-image img {
    width: 80px;
    height: 80px;
    border-radius: 8px; /* 图片圆角 */
    object-fit: cover; /* 确保图片比例正常 */
}

.container-content {
    margin-left: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.container-title {
    font-size: 16px;
    margin-bottom: 10px;
}

.container-dropdown {
    width: 150px;
}

.product-item-title {
    font-weight: bold;
    margin-left: 16px;
}

/* 确保 form-item 内容自适应宽度 */

.el-input__suffix {
    right: 21%;
}
.el-input__inner {
    width: 80%;
}

.el-form--inline .el-form-item {
    display: flex;
    justify-content: flex-start;
    width: 100%;
}

.el-form-item__content {
    width: 100%;
}

.el-collapse {
    border: 0px;
}

.el-collapse-item {
    border: 1px solid #dcdcdc;
    border-radius: 5px;
    margin: 20px 10px 0px 10px;
    overflow: hidden;
}

.el-collapse-item__content {
    padding-bottom: 10px;
}

.el-collapse-item__header .el-icon-arrow-right {
    display: none;
}

.el-collapse-item__header {
    height: 30px;
    padding-left: 4px;
    margin-left: 20px;
}

.el-collapse-item__header:before {
    content: "";
    width: 0;
    height: 0;
    border-top: 6px solid transparent;
    border-bottom: 6px solid transparent;
    border-left: 6px solid rgb(128, 128, 128);
    transition: transform 0.3s;
}

.is-active .el-collapse-item__header:before {
    transform: rotate(90deg);
}
</style>
